<?php

namespace App\Http\Controllers;

use App\Exports\ErpExport;
use App\Exports\SkuExport;
use App\Services\ErpService;
use Illuminate\Http\Request;

class ErpController extends Controller
{
    private $erp_service;
    public function __construct(ErpService $erp_service)
    {
        $this->erp_service = $erp_service;
    }
    public function index(){

        return view('erp', ['list'=> [], 'barcode' => '']);
    }

    /**
     * 仓库查询
     * @param Request $request
     */
    public function query(Request $request){

        if($request->method() == 'POST'){
            try{
                $barcode = trim(strip_tags($request->input('barcode', '')));
                if(empty($barcode)) throw new \Exception('参数异常', 20001);
                $data = $this->erp_service->query($barcode);
//                return $this->success($data);
                return view('erp', ['list' => $data, 'barcode' => $barcode]);
            }catch (\Exception $e){
                return $this->result($e->getCode(), $e->getMessage());
            }
        }else{
            return view('erp', ['list'=> [], 'barcode' => '']);
        }
    }

    /**
     * 导出查询结果
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function export(Request $request) {

        try{
            $barcode = trim(strip_tags($request->input('barcode', '')));
            if(empty($barcode)) throw new \Exception('参数异常', 20001);
            $records =  $this->erp_service->query($barcode);
            $export = new ErpExport($records);
            return \Excel::download($export, 'records-'.date('YmdHis', time()).'.xlsx');
        }catch (\Exception $e){
            return $this->result($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 导出组合的SKU库存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function exportSkus(Request $request){

        try{
            $barcode = trim(strip_tags($request->input('barcode', '')));
            if(empty($barcode)) throw new \Exception('参数异常', 20001);
            $records =  $this->erp_service->querySkus($barcode);
            $export = new SkuExport($records);
            return \Excel::download($export, 'skus-'.date('YmdHis', time()).'.xlsx');
        }catch (\Exception $e){
            return $this->result($e->getCode(), $e->getMessage());
        }
    }
}
